/*
 * Powered By xieming
 * Generated 2015-05-13
 */
package com.teamall.web.main.vo;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.teamall.core.common.CommonEnum;
import com.teamall.web.tssy.db.po.TsSyResourcePO;

public class IndexTree{
	private StringBuffer html = new StringBuffer(); 
	private List<TsSyResourcePO> nodes;
	private String webPath = "";
	
	
	public IndexTree(List<TsSyResourcePO> nodes){
		this.nodes = nodes;
	}
	
	public String buildTree(String webPath){
		this.webPath=webPath;
		html.append("<div id='bjui-hnav-navbar-box'>");
        html.append("<ul id='bjui-hnav-navbar'>");
        int i = 0;
        for (TsSyResourcePO node : nodes) { 
            if ("0".equals(node.getPid())) { 
            	if(i==0){
            		html.append("<li class='active'><a href='javascript:;' data-toggle='slidebar'><i class='fa fa-image'></i>"+node.getResourceName()+"</a>");
            	}else{
            		html.append("<li><a href='javascript:;' data-toggle='slidebar'><i class='fa fa-image'></i>"+node.getResourceName()+"</a>");
            	}
        		html.append("<div class='items hide' data-noinit='true'>");
        		html.append("<ul id='bjui-hnav-tree"+i+"' class='ztree ztree_main' data-toggle='ztree' data-on-click='MainMenuClick' data-expand-all='true' data-faicon='image'>");
        		build(node);  
                html.append("</ul></div></li>");  
                i++;
            }  
        } 
        html.append("</ul></div>");
        return html.toString();  
    }  
      
    private void build(TsSyResourcePO node){  
        List<TsSyResourcePO> children = getChildren(node);  
        if (!children.isEmpty()) {
        	for (TsSyResourcePO child : children) {  
                String id = child.getId();
                if(StringUtils.isNotEmpty(child.getUrl())){
                	html.append("<li data-id='" + id + "' data-pid='"+node.getId()+"' data-url='"+webPath+child.getUrl()+"' data-faicon='image' data-tabid='"+child.getRel()+"'>"+child.getResourceName());
                	html.append("</li>");
                }else{
                	html.append("<li data-id='" + id + "' data-pid='"+node.getId()+"' data-faicon='folder-open-o' data-faicon-close='folder-o'>"+child.getResourceName()+"");
                	html.append("</li>");
                }
                build(child); 
            } 
        }   
    }  
      
    private List<TsSyResourcePO> getChildren(TsSyResourcePO node){  
        List<TsSyResourcePO> children = new ArrayList<TsSyResourcePO>();  
        String id = node.getId();  
        for (TsSyResourcePO child : nodes) {  
            if (id.equals(child.getPid())) {  
                children.add(child);  
            }  
        }  
        return children;  
    }  
}

